package com.jshoperxms.controller.mall.backstage.basicuser;

import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.SHA1;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.BasicUserEnums;
import com.jshoperxms.controller.utils.statickey.*;
import com.jshoperxms.entity.*;
import com.jshoperxms.redis.RedisBaseOperation;
import com.jshoperxms.service.*;
import com.jshoperxms.shiro.LoginUsernamePasswordToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 
* @ClassName: BasicUserT 
* @Description: 后台基础用户操作
* @author jcchen
* @date 2015年10月28日 下午4:41:58 
*
 */
@Controller
@RequestMapping("/mall/basicuser")
public class BasicUserTController extends BaseTController implements IBaseCtrl<BasicUserT> {
	private static final Logger logger = LoggerFactory.getLogger(BasicUserTController.class);

	@Resource
	private BasicUserTService basicUserTService;

	@Resource
	private SysUserRoleRpTService sysUserRoleRpTService;

	@Resource
	private SysRoleTService sysRoleTService;

	@Resource
	private SysModuleActionTService sysModuleActionTService;

	@Resource
	private SysRoleModuleActionRpTService sysRoleModuleActionRpTService;


	@Resource
	private RedisBaseOperation<BasicUserT> redisBaseOperation;
	private Map<String, Object> responsedata = new HashMap<>();//数据形式


    /**
	 * 跳转到登录html
	 * @return
     */
	@RequestMapping(value = "/rlogin",method = RequestMethod.GET)
	public ModelAndView redirectToLogin(){
		return new ModelAndView("/login.html");
	}



	/**
	 * 后台管理者登录
	 * @return
	 */
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity login(HttpServletRequest request, @RequestBody BasicUserT bt){
		if (StringUtils.isBlank(bt.getUsername())) {
			responsedata.put(TagWords.MSG,WarnWrods.EMPTY_LOGINNAME);
			responsedata.put(TagWords.SUCCESS, false);


		}
		if (StringUtils.isBlank(bt.getPassword())) {
			responsedata.put(TagWords.MSG,WarnWrods.EMPTY_LOGINPWD);
			responsedata.put(TagWords.SUCCESS, false);
		}

//		String username=bt.getUsername();
//		LoginUsernamePasswordToken token=new LoginUsernamePasswordToken(bt.getUsername(),bt.getPassword());
//		//获取当前的subject
//		Subject currentUser= SecurityUtils.getSubject();
//		try{
//			currentUser.login(token);
//		}catch(UnknownAccountException uae){
//			logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
//			responsedata.put(TagWords.MSG,"未知账号");
//		}catch (IncorrectCredentialsException ice){
//			logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
//			responsedata.put(TagWords.MSG,"密码不正确");
//		}catch (LockedAccountException lae){
//			logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
//			responsedata.put(TagWords.MSG,"账户已锁定");
//		}catch(ExcessiveAttemptsException eae){
//			logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
//			responsedata.put(TagWords.MSG,"用户名或密码错误次数过多");
//		}catch (AuthenticationException ae){
//			logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
//			ae.printStackTrace();
//			responsedata.put(TagWords.MSG,"用户名或密码不正确");
//		}

//		if(currentUser.isAuthenticated()){
//			logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
			BasicUserT basicUserT=new BasicUserT();
			basicUserT.setUsername(StringUtils.trim(bt.getUsername()));
			basicUserT.setPassword(SHA1.getDigestOfString(bt.getPassword()));
			basicUserT.setUserstatus(BasicUserEnums.UserStatus.ACTIVE.getState());
			basicUserT.setStatus(BaseEnums.DataUsingState.USING.getState());
			Map<String,String>params=new HashMap<String,String>();
			params.put("username", StringUtils.trim(bt.getUsername()));
			params.put("password", SHA1.getDigestOfString(bt.getPassword()));
			params.put("userstatus", BasicUserEnums.UserStatus.ACTIVE.getState());
			params.put("status", BaseEnums.DataUsingState.USING.getState());
			Criterion criterion=Restrictions.allEq(params);
			basicUserT=this.basicUserTService.findOneByCriteria(BasicUserT.class, criterion);
			if(basicUserT!=null){
				doSysIndexInit(basicUserT,request);
				doSysUserRole(basicUserT);
				responsedata.put(TagWords.SUCCESS, true);
			}
//		}else{
//			token.clear();
//			responsedata.put(TagWords.SUCCESS,false);
//		}

//		BasicUserT basicUserT=new BasicUserT();
//		basicUserT.setUsername(StringUtils.trim(bt.getUsername()));
//		basicUserT.setPassword(SHA1.getDigestOfString(bt.getPassword()));
//		basicUserT.setUserstatus(BasicUserEnums.UserStatus.ACTIVE.getState());
//		basicUserT.setStatus(BaseEnums.DataUsingState.USING.getState());
//		Map<String,String>params=new HashMap<String,String>();
//		params.put("username", StringUtils.trim(bt.getUsername()));
//		params.put("password", SHA1.getDigestOfString(bt.getPassword()));
//		params.put("userstatus", BasicUserEnums.UserStatus.ACTIVE.getState());
//		params.put("status", BaseEnums.DataUsingState.USING.getState());
//		Criterion criterion=Restrictions.allEq(params);
//		basicUserT=this.basicUserTService.findOneByCriteria(BasicUserT.class, criterion);
//		if(basicUserT!=null){
//			doSysIndexInit(basicUserT,request);
//			responsedata.put(TagWords.SUCCESS, true);
//		}else{
//			responsedata.put(TagWords.MSG,WarnWrods.EMPTY_ACCOUNT);
//		}

		return Response.success(responsedata);
	}
	
	/**
	 * 进行用户登录有的系统首页数据初始化及用户权限相关初始化
	 */

	private void doSysIndexInit(BasicUserT basicUserT,HttpServletRequest request) {
		request.getSession().setAttribute(StaticKey.BACK_USER_SESSION_KEY, basicUserT);
		responsedata.put(TagWords.TOKEN,basicUserT.getId());
		responsedata.put(TagWords.BEAN,basicUserT);
		redisBaseOperation.saveOrUpdate(basicUserT.getId(),basicUserT,RedisKey.MEMBERTIMEOUTTHREEM,TimeUnit.MINUTES);
	}


	private void doSysUserRole(BasicUserT basicUserT) {
		//获取用户的所有角色,和权限
		List<SysModuleActionT> userPermissions=new ArrayList<>();
		Criterion criterion2 = Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState());
		criterion2 = Restrictions.and(criterion2).add(Restrictions.eq("basicuserid", basicUserT.getId()));
		List<SysUserRoleRpT> list = this.sysUserRoleRpTService.findByCriteria(SysUserRoleRpT.class, criterion2);
		if (!list.isEmpty()) {
			for (SysUserRoleRpT s : list) {
				SysRoleT bean = this.sysRoleTService.findByPK(SysRoleT.class, s.getSysroleid());
				if (bean != null) {
					//获取角色权限信息
					Criterion criterion1=Restrictions.eq("sysroleid",bean.getId());
					List<SysRoleModuleActionRpT>sysRoleModuleActionRpTs=this.sysRoleModuleActionRpTService.findByCriteria(SysRoleModuleActionRpT.class,criterion1);
					if(!sysRoleModuleActionRpTs.isEmpty()){
						for(SysRoleModuleActionRpT s1:sysRoleModuleActionRpTs){
							SysModuleActionT sysm=this.sysModuleActionTService.findByPK(SysModuleActionT.class,s1.getSysmoduleactionid());
							if(sysm!=null){
								userPermissions.add(sysm);
							}
						}

					}
				}
			}
		}
		responsedata.put(TagWords.PERMISSIONS, userPermissions);
	}



	@RequestMapping(value="/save",method= RequestMethod.POST)
	@Override
	public ResponseEntity save(@RequestBody BasicUserT rq) {
		if(checkDuplicates(rq.getUsername())) {
			BasicUserT bean = new BasicUserT();
			bean.setId(this.serial.Serialid(SerialKeys.BasicUserT));
			bean.setCreatetime(DateTools.getSystemTimeBi());
			bean.setCreatorid(BaseTools.getAdminCreateId());
			bean.setDepartment(StaticKey.EMPTY);
			bean.setEmail(rq.getEmail());
			bean.setGroupid(StaticKey.EMPTY);
			Map<String,String>map=BaseTools.parseImg(rq.getMainimg());
			bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
			bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
			bean.setIp(StaticKey.EMPTY);
			bean.setIstemp(rq.getIstemp());
			bean.setLasttime(DateTools.getSystemTimeBi());
			bean.setMobile(rq.getMobile());
			bean.setPassword(SHA1.getDigestOfString(rq.getPassword()));
			bean.setRank("super");//super可无视权限控制,超级用户
			bean.setRegistertime(DateTools.getSystemTimeBi());
			bean.setStatus(BaseEnums.DataUsingState.USING.getState());
			bean.setTeamid(StaticKey.EMPTY);
			bean.setType(StaticKey.EMPTY);
			bean.setUid(SHA1.getDigestOfString(bean.getId()));
			bean.setUpdatetime(DateTools.getSystemTimeBi());
			bean.setUsername(rq.getUsername());
			bean.setUserstatus(rq.getUserstatus());
			bean.setSysrole(StaticKey.EMPTY);
			bean.setVersiont(1);
			bean.setSalt(rq.getUsername());
			this.basicUserTService.save(bean);
			responsedata.put(TagWords.SUCCESS, true);
			responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
		}else {
			responsedata.put(TagWords.SUCCESS, false);
			responsedata.put(TagWords.MSG, WarnWrods.ERROR_HAVE_KEY);
		}
		return Response.success(responsedata);
	}

	@RequestMapping(value="/find",method= RequestMethod.POST)
	@Override
	public ResponseEntity find(@RequestBody BasicUserT rq) {
		if(StringUtils.isBlank(rq.getId())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
		}else{
			BasicUserT bean=this.basicUserTService.findByPK(BasicUserT.class,rq.getId());
			if(bean!=null){
				ImgFileBean ifb=new ImgFileBean();
				ifb.setNormalfilepath(bean.getMainimg());
				ifb.setCompressfilepath(bean.getSmainimg());
				ifb.setBasepath(StaticKey.EMPTY);
				responsedata.put(TagWords.IFB,ifb);
				responsedata.put(TagWords.BEAN,bean);
				responsedata.put(TagWords.SUCCESS,true);
				responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
			}else{
				responsedata.put(TagWords.SUCCESS,false);
				responsedata.put(TagWords.MSG,TagWords.INVALIDDATA);
			}
		}
		return Response.success(responsedata);
	}

	@RequestMapping(value="/del",method= RequestMethod.POST)
	@Override
	public ResponseEntity del(@RequestBody BasicUserT rq) {
		if(StringUtils.isBlank(rq.getId())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}else{
			String ids[]=StringUtils.split(rq.getId(), TagWords.SPLITDOT);
			for(String s:ids){
				BasicUserT bean=this.basicUserTService.findByPK(BasicUserT.class, s);
				if(bean!=null){
					bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
					bean.setUpdatetime(DateTools.getSystemTimeBi());
					this.basicUserTService.update(bean);
				}
			}
			responsedata.put(TagWords.SUCCESS,true);
			responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
		}
		return Response.success(responsedata);
	}

	@RequestMapping(value="/update",method= RequestMethod.POST)
	@Override
	public ResponseEntity update(@RequestBody BasicUserT rq) {
		if(StringUtils.isBlank(rq.getId())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}else{
			BasicUserT bean=this.basicUserTService.findByPK(BasicUserT.class,rq.getId());
			if(bean!=null){
				bean.setEmail(rq.getEmail());
				Map<String,String>map=BaseTools.parseImg(rq.getMainimg());
				bean.setMainimg(map.get(TagWords.NORMALFILEPATH));
				bean.setSmainimg(map.get(TagWords.COMPRESSFILEPATH));
				bean.setIstemp(rq.getIstemp());
				bean.setMobile(rq.getMobile());
				bean.setUserstatus(rq.getUserstatus());
				bean.setVersiont(bean.getVersiont()+1);
				this.basicUserTService.update(bean);
				responsedata.put(TagWords.SUCCESS, true);
				responsedata.put(TagWords.MSG, TagWords.OPERATION_SUCCESS);
			}
		}
		return Response.success(responsedata);
	}

	@Override
	public ResponseEntity findAll() {
		return null;
	}


	@RequestMapping(value="/findByPage",method= RequestMethod.POST)
	@Override
	public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
		findCustomSearch(searchModel,search,ordervalue,ordertype);
		return Response.success(responsedata);
	}

	@Override
	public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
		if(searchModel.getIsCustomSearch()==1){
			int currentPage=searchModel.getCalCurrentPage();
			int lineSize = searchModel.getLength();
			Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
			if(StringUtils.isNotBlank(searchModel.getName())){
				criterion=Restrictions.and(criterion).add(Restrictions.like("username",searchModel.getName(), MatchMode.ANYWHERE));
			}
			if(StringUtils.isNotBlank(search)){
				criterion=Restrictions.and(criterion).add(Restrictions.like("username",search,MatchMode.ANYWHERE));
			}
			int records=this.basicUserTService.count(BasicUserT.class,criterion).intValue();
			searchModel.setRecordsTotal(records);
			searchModel.setRecordsFiltered(records);
			responsedata.put(TagWords.RECORDSTOTAL,records);
			responsedata.put(TagWords.RECORDSFILTERED,records);
			List<BasicUserT> list = this.basicUserTService.findByCriteriaByPage(
					BasicUserT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
					lineSize);
			this.processPageList(list);
		}else{
			if(StringUtils.isNotBlank(search)){
				filterSearch(searchModel,search);
			}else{
				findDefaultAll(searchModel,ordervalue,ordertype);
			}
		}
	}

	@Override
	public void filterSearch(SearchModel searchModel, String search) {
		int currentPage=searchModel.getCalCurrentPage();
		int lineSize = searchModel.getLength();
		Criterion criterion;
		Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
		Criterion criterion2=Restrictions.like("username",search,MatchMode.ANYWHERE);
		criterion=Restrictions.and(criterion1).add(criterion2);
		int records=this.basicUserTService.count(BasicUserT.class,criterion).intValue();
		searchModel.setRecordsTotal(records);
		searchModel.setRecordsFiltered(records);
		responsedata.put(TagWords.RECORDSTOTAL,records);
		responsedata.put(TagWords.RECORDSFILTERED,records);
		List<BasicUserT> list = this.basicUserTService.findByCriteriaByPage(
				BasicUserT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
				lineSize);
		this.processPageList(list);
	}

	@Override
	public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
		int currentPage=searchModel.getCalCurrentPage();
		int lineSize = searchModel.getLength();
		Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
		int records=this.basicUserTService.count(BasicUserT.class,criterion).intValue();
		searchModel.setRecordsFiltered(records);
		searchModel.setRecordsTotal(records);
		responsedata.put(TagWords.RECORDSTOTAL,records);
		responsedata.put(TagWords.RECORDSFILTERED,records);
		Order order=BaseTools.orderByParam("username",ordervalue,ordertype);
		List<BasicUserT> list = this.basicUserTService.findByCriteriaByPage(
				BasicUserT.class, criterion,order, currentPage,
				lineSize);
		this.processPageList(list);
	}

	@Override
	public void processPageList(List<BasicUserT> list) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (BasicUserT bean:list) {
			Map<String, Object> cellMap = new HashMap<String, Object>();
			cellMap.put("id", bean.getId());
			cellMap.put("username", bean.getUsername());
			cellMap.put("mobile",bean.getMobile());
			cellMap.put("sysrole",bean.getSysrole());
			cellMap.put("registertime",DateTools.formateLongDateToString(bean.getRegistertime().longValue()));
			cellMap.put("userstatus", BasicUserEnums.UserStatus.getName(bean.getUserstatus()));
			cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
			cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
			cellMap.put("version", bean.getVersiont());
			data.add(cellMap);
		}
		responsedata.put(TagWords.DATA, data);
	}

	@Override
	public boolean checkDuplicates(String str) {
		Criterion criterion=Restrictions.eq("username",str);
		BasicUserT bean=this.basicUserTService.findOneByCriteria(BasicUserT.class,criterion);
		if(bean!=null){
			return false;
		}
		return true;
	}



	@RequestMapping(value="/logout",method=RequestMethod.POST)
	public ResponseEntity logout(){
		//使用权限管理工具进行用户的退出，跳出登录，给出提示信息
		SecurityUtils.getSubject().logout();
		responsedata.put(TagWords.SUCCESS,true);
		responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
		return Response.success(responsedata);
	}


}
